/**
 * Copyright (C) 2007 The AsyncMail Group <asyncmail@googlegroups.com>
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *         http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.googlecode.asyncmail.smtp.filter;

import org.apache.mina.common.IoFilterAdapter;
import org.apache.mina.common.IoSession;

import com.googlecode.asyncmail.smtp.SMTPRequest;
import com.googlecode.asyncmail.smtp.SMTPRequestImpl;
import com.googlecode.asyncmail.smtp.SMTPResponseImpl;

/**
 * Filter to convert SMTPResponse to String Objects
 * 
 */
public class SMTPRequestFilter extends IoFilterAdapter {

    @Override
    public void messageReceived(NextFilter arg0, IoSession arg1, Object arg2)
            throws Exception {
        if (arg2 instanceof String) {
            SMTPResponseImpl resp = (SMTPResponseImpl) arg1
                    .getAttribute("CURRENT_RESPONSE");
            if (resp == null) {
                resp = new SMTPResponseImpl();
                resp.setRetCode(((String) arg2).substring(0, 3));
                arg1.setAttribute("CURRENT_RESPONSE", resp);
            }
            resp.appendLine(((String) arg2).substring(4));
            if (!((String) arg2).substring(3, 4).equals("-")) {
                arg0.messageReceived(arg1, resp);
                arg1.removeAttribute("CURRENT_RESPONSE");
            }
        } else {
            super.messageReceived(arg0, arg1, arg2);
        }
    }

    @Override
    public void filterWrite(NextFilter arg0, IoSession arg1,
            WriteRequest writeRequest) throws Exception {

        if (writeRequest.getMessage() instanceof SMTPRequestImpl) {
            SMTPRequest req = (SMTPRequest) writeRequest.getMessage();
            StringBuffer line = new StringBuffer();
            line.append(req.getCommand());
            if (req.getArgument() != null && req.getArgument().length() > 0) {
                line.append(" ");
                line.append(req.getArgument());
            }
            arg0.filterWrite(arg1, new WriteRequest(line.toString()));
        } else {
            arg0.filterWrite(arg1, writeRequest);
        }

    }
}
